// 登录界面
<template>
  <div class="container">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="userName" required>
        <el-input
          v-model="ruleForm.userName"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password" required>
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          style="width:100px"
          >登录</el-button
        >
        <el-button @click="resetForm('ruleForm')" style="width:100px"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    // 用户名
    var validateUserName = (rule, value, callback) => {
      var reg = /^[\u4e00-\u9fa5]+$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!reg.test(value)) {
        callback(new Error("用户名只能输入中文"));
      } else {
        callback();
      }
    };
    // 密码
    var validatePass = (rule, value, callback) => {
      
      if (value === "") {
        callback(new Error("请输入密码"));
      } else{
        callback();
      }
    };
    return {
      ruleForm: {
        userName: "",
        password: "",
      },
      rules: {
        userName: [{ validator: validateUserName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch("login/login", this.ruleForm).then((resp) => {
            if (resp) {
              this.$message("登录成功", 2000);
              this.$router.push({ name: "Home" });
            } else {
              // 登录失败
              this.$message("登录失败", 2000);
              this.$router.push({ name: "Login" });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.container {
  margin-top: 20px;
  width: 30%;
}
</style>
